#include "xtask.h"
#include "xtimer.h"
#include "xthread_manager.h"
#include "xthread_debug.h"
#include "xtimer.h"
namespace xge{
namespace xge_internal{

  bool Task::Join() {
    // Join the task 
    XASSERT( bind_type_ == REMOTE_BINDING );
    XASSERT_SLOW( ThreadDebug::IsInMainThread() );
    while( task_status_ != TASK_STATUS_RELEASE ) {
      // if the task status is not RELEASE
      // so there must be a worker queue is waiting for the CPU time to run the task
      // give up the cpu time now
      ThreadManager::SwithToAnotherThread();
    }
    return true;
  }

  const TripleResult Task::Join( int ms ) {
    // Join the task 
    XASSERT( bind_type_ == REMOTE_BINDING );
    XASSERT_SLOW( ThreadDebug::IsInMainThread() );
    Timer timer;
    if( !timer.BeginTimerCounting() ) {
      return TripleResult::kException;
    }
    Timer::tick_t elapse;
    while( task_status_ != TASK_STATUS_RELEASE ) {
      elapse+=timer.TimeDiff();
      if( elapse > (size_t)(ms) ) {
        return TripleResult::kFailed;
      }
      ThreadManager::SwithToAnotherThread();
    }
    return TripleResult::kSucceded;

  }


}// namespace xge_internal
}//namespace xge


